package com.xukai.springboot.filter;

import com.xukai.springboot.util.common.Common;
import com.xukai.springboot.constants.SysConstant;
import com.xukai.springboot.util.session.SessionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * 安全身份filter
 */
@Service
public class SecurityFilter implements Filter {
    /**
     *
     */
    private static final Logger logger = LoggerFactory.getLogger(SecurityFilter.class);

    @Autowired
    SessionService sessionService;

    /**
     * 封装，不需要过滤的list列表
     */
    protected static List<String> patterns = new ArrayList<String>();

    public List<String> getPatterns() {
        return patterns;
    }

    private int isDebug = 0;

    public int getIsDebug() {
        return isDebug;
    }

    public void setIsDebug(int isDebug) {
        this.isDebug = isDebug;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        HttpServletRequest req = (HttpServletRequest) servletRequest;

        String Token = req.getHeader("token");

        String openID = (Token == null || Token.isEmpty()) ? servletRequest.getParameter("openID") : Token;
        String span = servletRequest.getParameter("span");
        String sign = servletRequest.getParameter("sign");


        if (isDebug == 1) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        if (openID == null || span == null || sign == null) {
            SendError(resp, "请求失败，没有接口访问权限");
            return;
        }

        if (sessionService.checkToken()) {
            SendError(resp, "token验证失败，没有接口访问权限");
            return;
        }

        if (Common.getInstance().checkSign(sign, isDebug, openID, span, SysConstant.privateKey)) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            SendError(resp, "请求失败，没有接口访问权限");
            return;
        }
    }

    @Override
    public void destroy() {

    }


    private void SendError(HttpServletResponse resp, String msg) {
        try {
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter writer = resp.getWriter();
            writer.write("{" +
                    "  \"statue\":0," +
                    "  \"errMessage\": \"" + msg + "\"" +
                    "}");
            writer.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
